﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace PhoneNumberOrder
{
    public partial class HistoryPhoneNumSearchFrm : Form
    {
        private bool m_OnlyLast4 = false;
        private string m_Filter = "";
        private string m_RuleFilter = "";
        public HistoryPhoneNumSearchFrm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.m_RuleFilter = "";
            if(this.comboBox1.SelectedIndex > 0)
            {
                this.m_RuleFilter = this.comboBox1.SelectedValue.ToString();
            }

            m_Filter = this.textBox1.Text;
            this.m_OnlyLast4 = this.checkBox1.Checked;
            int recordCount = this.getCount();
            this.pagerCtrl1.SetRecordCount(recordCount, true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = "";
            this.checkBox1.Checked = false;
            button1_Click(null, null);
        }

        private void pagerCtrl1_OnRefreshClick(object sender, EventArgs e)
        {
            int firstNum = this.pagerCtrl1.PageSzie * (this.pagerCtrl1.CurrPageIndex - 1) + 1;
            int lastNum = this.pagerCtrl1.PageSzie * (this.pagerCtrl1.CurrPageIndex);
            int num = 0;
            int index = -1;
            if (this.m_OnlyLast4)
                index += 7;
            Dictionary<string, IList> historyPhoneList = MainFrm.self.getHistoryPhoneList();

            this.dataGridView1.Rows.Clear();
            DataGridViewRow row;
            foreach (string ruleKey in historyPhoneList.Keys)
            {
                IList list = historyPhoneList[ruleKey];

                for (int i = 0; i < list.Count; i++)
                {
                    PhoneOrder phone = (PhoneOrder)list[i];
                    bool isOk = true;
                    if (m_Filter != "" && phone.m_Num.IndexOf(m_Filter) <= index)
                        isOk = false;

                    if (m_RuleFilter != "" && phone.m_RuleParam != m_RuleFilter)
                        isOk = false;

                    if (isOk)
                    {
                        num++;
                        if (num >= firstNum && num <= lastNum)
                        {
                            this.dataGridView1.Rows.Add();

                            row = this.dataGridView1.Rows[this.dataGridView1.RowCount - 1];
                            row.Cells[0].Value = phone.m_RuleParam;
                            row.Cells[1].Value = phone.m_Num;
                            row.Cells[2].Value = phone.m_PrestoreMoney;
                            row.Cells[3].Value = phone.m_BaseFeeMoney;
                            row.Tag = phone;
                        }
                    }
                }

            }
        }

        private int getCount()
        {
            int iCount = 0;
            int index = -1;
            if (this.m_OnlyLast4)
                index += 7;
            Dictionary<string, IList> historyPhoneList = MainFrm.self.getHistoryPhoneList();
            foreach (string ruleKey in historyPhoneList.Keys)
            {
                IList list = historyPhoneList[ruleKey];
                if (m_Filter != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        PhoneOrder phone = (PhoneOrder)list[i];
                        if (phone.m_Num.IndexOf(m_Filter) > index)
                            iCount++;
                    }
                }
                else
                {
                    iCount += list.Count;
                }
            }

            return iCount;
        }

        private void HistoryPhoneNumSearchFrm_Load(object sender, EventArgs e)
        {
            button1_Click(null, null);
            this.timer1.Enabled = true;
            MainFrm.self.loadRuleComboBox(this.comboBox1);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                button1_Click(null, null);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //int iCount = this.getCount();
            //if (iCount > this.pagerCtrl1.RecordCount)
            //{
            //    this.pagerCtrl1.SetRecordCount(recordCount, false);
            //}
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("号码规则");
            dt.Columns.Add("手机号码");
            dt.Columns.Add("预存");
            dt.Columns.Add("低消");

            int index = 0;
            if (this.m_OnlyLast4)
                index += 7;
            DataRow row;
            Dictionary<string, IList> historyPhoneList = MainFrm.self.getHistoryPhoneList();
            foreach (string ruleKey in historyPhoneList.Keys)
            {
                IList list = historyPhoneList[ruleKey];

                for (int i = 0; i < list.Count; i++)
                {
                    PhoneOrder phone = (PhoneOrder)list[i];
                    if (m_Filter != null)
                    {
                        if (phone.m_Num.IndexOf(m_Filter) < index)
                            continue;
                    }

                    row = dt.NewRow();
                    row[0] = phone.m_RuleParam;
                    row[1] = phone.m_Num;
                    row[2] = phone.m_PrestoreMoney;
                    row[3] = phone.m_BaseFeeMoney;
                    dt.Rows.Add(row);
                }
            }

            MainFrm.RenderToExcel(dt);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择号码");
                return;
            }
            string phoneRule = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            string phoneNum = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
            string strPrePrice = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
            string strBaseFee = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
            PhoneOrder phone = (PhoneOrder)this.dataGridView1.CurrentRow.Tag;
            string[] temp_car = MainFrm.self.lockNum(phoneRule, phoneNum, strPrePrice, strBaseFee, phone.m_CityId);
            if (temp_car != null && temp_car[2] == "true")
                MainFrm.self.showProductCar(temp_car[0], temp_car[1], phone.m_Num, phone.m_CityId, temp_car[3]);
            else
            {
                MessageBox.Show("号码锁定失败！如果是之前锁定号码，请锁定号码查询功能再试！");
            }
        }

        public string getSocketReceiveText(Socket socket, string strEndTag)
        {
            string strResult = "";
            StringBuilder sb = new StringBuilder();
            socket.ReceiveTimeout = 5 * 1000;//5秒阻塞
            byte[] receivedBytes = new byte[1024 * 100];
            try
            {
                int receiveCount = 0;
                int totelCount = 0;
                while (true)
                {
                    receiveCount = socket.Receive(receivedBytes, totelCount, receivedBytes.Length - totelCount, SocketFlags.None);
                    totelCount += receiveCount;
                    strResult = Encoding.GetEncoding("GB2312").GetString(receivedBytes);
                    if (strResult.Contains(strEndTag))
                    {
                        string strPattern = "\r\n[0-9a-f]{1,}\r\n";
                        Regex reg = new Regex(strPattern, RegexOptions.IgnoreCase);
                        strResult = reg.Replace(strResult, "");
                        break;
                    }
                    if (receiveCount == 0)
                        throw new Exception("连接已经连开！");
                }
            }
            catch (Exception)
            {
                throw new Exception("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！");
            }
            finally
            {
                socket.Close();
            }

            return strResult;
        }
    }
}